import CryptoJS from "crypto-js";
/***
 * R-ZBZB-202109030777584-铁塔换电平台-骑手敏感信息泄露优化
 */
import store from "@/store";
import moment from "moment";

const obsInfoPlaintext = {};
export default {
  obsEncryption: function (url) {
    if (store.getters.obsInfo == undefined) {
      //获取的obs加密信息为空 则返回url
      return url;
    }
    obsInfoPlaintext.ak = store.getters.obsInfo.ak;
    obsInfoPlaintext.sk = store.getters.obsInfo.sk;
    obsInfoPlaintext.timesTamp = store.getters.obsInfo.timesTamp;
    obsInfoPlaintext.endPoint = store.getters.obsInfo.endPoint;
    let key =
      "china.tower" +
      obsInfoPlaintext.timesTamp.substr(8, obsInfoPlaintext.timesTamp.length);
    key = CryptoJS.enc.Utf8.parse(key);
    obsInfoPlaintext.ak = this.decrypt2(obsInfoPlaintext.ak, key);
    obsInfoPlaintext.sk = this.decrypt2(obsInfoPlaintext.sk, key);
    let expires = ((new Date().valueOf() + 600 * 1000) / 1000).toString(); //过期时间60s  最后单位切换成s
    expires = expires.substring(0, expires.indexOf("."));
    let bucketName = url.substring(url.indexOf("//") + 2, url.indexOf("."));
    let objectName = "";
    if (url.indexOf(":443/") > 0) {
      objectName = url.substring(url.indexOf(":443/") + 5, url.length);
    } else {
      objectName = url.substring(url.indexOf(".com/") + 5, url.length);
    }

    let stringToSign =
      "GET" +
      "\n" +
      "" +
      "\n" +
      "" +
      "\n" +
      expires +
      "\n" +
      "/" +
      bucketName +
      "/" +
      objectName;
    let signature = this.hmacstr(stringToSign, obsInfoPlaintext.sk);
    return "".concat(
      "https://",
      bucketName,
      ".",
      obsInfoPlaintext.endPoint,
      "/",
      objectName,
      "?",
      "AccessKeyId=",
      obsInfoPlaintext.ak,
      "&Expires=",
      expires,
      "&Signature=",
      signature
    );
  },

  /**
   * 加自定义密钥的
   * @param content
   * @returns {string}
   */
  hmacstr: function (msg, key) {
    let result = CryptoJS.HmacSHA1(msg, key);
    let sig = result.toString(CryptoJS.enc.Base64);
    sig = encodeURI(sig);
    sig = encodeURIComponent(sig)
      .replaceAll("%7E", "~") //for browser
      .replaceAll("%2F", "/");
    return sig;
  },

  /**
   * 自定义key的解密
   * [decrypt 解密]
   * @return {[type]} [description]
   */
  decrypt2(content, key) {
    var encryptedHexStr = CryptoJS.enc.Base64.parse(content);
    var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return decryptedData.toString(CryptoJS.enc.Utf8);
  },
};
